package com.itheima.stock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.stock.entity.*;
import com.itheima.stock.enums.Code;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.mapper.*;
import com.itheima.stock.properties.MarketIndexProperties;
import com.itheima.stock.response.ResponseResult;
import com.itheima.stock.service.StockService;
import com.itheima.stock.util.DateTimeUtil;
import com.itheima.stock.vo.*;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@Service
public class StockServiceImpl implements StockService {


    private final StockBlockRtInfoMapper blockRtInfoMapper;


    private final StockMarketIndexInfoMapper marketIndexInfoMapper;

    private final StockMarketLogPriceMapper marketLogPriceMapper;

    private final StockBusinessMapper stockBusinessMapper;
    private final MarketIndexProperties marketIndexProperties;
    private final StockRtInfoMapper stockRtInfoMapper;

    public StockServiceImpl(StockBlockRtInfoMapper blockRtInfoMapper, StockMarketIndexInfoMapper marketIndexInfoMapper, StockMarketLogPriceMapper marketLogPriceMapper, StockBusinessMapper stockBusinessMapper, MarketIndexProperties marketIndexProperties, StockRtInfoMapper stockRtInfoMapper) {
        this.blockRtInfoMapper = blockRtInfoMapper;
        this.marketIndexInfoMapper = marketIndexInfoMapper;
        this.marketLogPriceMapper = marketLogPriceMapper;
        this.stockBusinessMapper = stockBusinessMapper;
        this.marketIndexProperties = marketIndexProperties;
        this.stockRtInfoMapper = stockRtInfoMapper;
    }



    @Override
    public UpDownVO<OptionVO> upDown() {
    LocalDateTime lsat = DateTimeUtil.getLastDateTime4Stock(LocalDateTime.now());
    // TODO:模拟数据
    LocalDateTime begin = LocalDateTime.parse("2022-01-06 09:25:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    LocalDateTime end = LocalDateTime.parse("2022-01-06 14:25:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    // TODO:模拟数据
    List<OptionVO> upList = stockRtInfoMapper.selectUpOrDown(begin, end, true);
    List<OptionVO> downList = stockRtInfoMapper.selectUpOrDown(begin, end, false);

    return UpDownVO.<OptionVO>builder()
            .upList(upList)
            .downList(downList)
            .build();
}


    @Override
    public ResponseResult<PageResult<IncreaseVO>> stockPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<IncreaseVO> infos= stockRtInfoMapper.stockAll();
        if (CollectionUtils.isEmpty(infos)) {
            return ResponseResult.error(CodeEnum.NO_RESPONSE_DATA);
        }

        PageInfo<IncreaseVO> listPageInfo = new PageInfo<>(infos);
        PageResult<IncreaseVO> pageResult = new PageResult<>(listPageInfo);

        return ResponseResult.ok(pageResult);
    }

    @Override
    public List<IncreaseVO> stockIncrease() {

        LocalDateTime last = DateTimeUtil.getLastDateTime4Stock(LocalDateTime.now());
        //TODO:模拟数据
        last=LocalDateTime.parse("2021-12-30 09:32:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //TODO:模拟数据
        List<StockRtInfo> stockRtInfoList = stockRtInfoMapper.selectByDateTime(last);
        List<IncreaseVO> result = new ArrayList<>();
        stockRtInfoList.stream().forEach (stock -> {
            IncreaseVO vo = new IncreaseVO();
            vo.setCode(stock.getStockCode());
            vo.setName(stock.getStockName());
            vo.setTradePrice(stock.getCurPrice());
            vo.setTradeAmt(stock.getTradeAmount());
            vo.setPreClosePrice(stock.getPreClosePrice());
            vo.setTradeVol(stock.getTradeVolume());
            vo.setCurDate(stock.getCurTime().toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            BigDecimal increase = (stock.getCurPrice().subtract(stock.getPreClosePrice())).divide(stock.getPreClosePrice(),new MathContext(6)).multiply(new BigDecimal(1.0));
            BigDecimal upDown = stock.getCurPrice().subtract(stock.getPreClosePrice());
            BigDecimal range=(stock.getMaxPrice().subtract(stock.getMinPrice())).divide(stock.getPreClosePrice(),new MathContext(6)).multiply(new BigDecimal(1.0));
            vo.setIncrease(increase);
            vo.setUpDown(upDown);
            vo.setAmplitude(range);
            result.add(vo);
        });
        List<IncreaseVO> list = result.stream().sorted((o1, o2) -> o2.getIncrease().compareTo(o1.getIncrease())).limit(10).toList();
        return list;
    }


    @Override
    public List<SectorAllVO> sectorAll() {
        LocalDateTime last = DateTimeUtil.getLastDateTime4Stock(LocalDateTime.now());

        //TODO:模拟数据
        last=LocalDateTime.parse("2021-12-21 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime begin= DateTimeUtil.getOpenDate(last);
        LocalDateTime end= DateTimeUtil.getCloseDate(last);

        //TODO:模拟数据

      List<StockBlockRtInfo> blockRtInfoList =  blockRtInfoMapper.selectByDateTimeDesc(begin,end);

        return blockRtInfoList.stream().map((blockRtInfo) -> SectorAllVO.builder()
                  .name(blockRtInfo.getBlockName())
                  .code(blockRtInfo.getLabel())
                  .companyNum(blockRtInfo.getCompanyNum())
                  .avgPrice(blockRtInfo.getAvgPrice())
                  .tradeAmt(blockRtInfo.getTradeAmount())
                  .curDate(blockRtInfo.getCurTime().toLocalDate().toString())
                  .build()).toList();

    }

    @Override
    public List<MarketIndexVO> innerIndexAll() {
        List<String> ids = marketIndexProperties.getInner();
     LocalDateTime lsat=DateTimeUtil.getLastDateTime4Stock(LocalDateTime.now());
     //以下为模拟数据
        String mockDate="20211226105600";
        lsat=LocalDateTime.parse(mockDate, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        List<StockMarketIndexInfo> stockMarketIndexInfoList = marketIndexInfoMapper.selectByIdsAndTime(ids,lsat);
        List<StockMarketLogPrice> stockMarketLogPriceList = marketLogPriceMapper.selectByIdsAndDate(ids,lsat.toLocalDate());


        return stockMarketIndexInfoList.stream().map(info -> {
            MarketIndexVO vo = MarketIndexVO.builder().build();
            vo.setCode(info.getMarkId());
            vo.setName(info.getMarkName());
            vo.setCurDate(info.getCurTime().toString());
            vo.setTradePrice(info.getCurrentPrice());
            vo.setTradeVol(info.getTradeVolume());
            vo.setUpDown(info.getUpdownRate());
            stockMarketLogPriceList.forEach(logPrice -> {
                if (info.getMarkId().equals(logPrice.getMarketCode())) {
                    vo.setPreClosePrice(logPrice.getPreClosePrice());
                    vo.setOpenPrice(logPrice.getOpenPrice());
                }else  {
                    vo.setPreClosePrice(BigDecimal.ZERO);
                    vo.setOpenPrice(BigDecimal.ZERO);
                }
            });
            return vo;
        }).toList();


    }

    @Override
    public List<StockBusiness> getStockBusiness() {

        return stockBusinessMapper.selectAll();
    }
}

